import jwt
from jwt import InvalidTokenError
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from education.models import User
from my_education.settings import SECRET_KEY


class LoginRequiredAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                # 先验证用户签名，通过后解码拿出用户信息
                payload = jwt.decode(token, SECRET_KEY)
                user = User()
                user.no = payload['userid']
                # 验证通过返回用户和令牌构成的二元组
                return user, token
            except InvalidTokenError:
                raise AuthenticationFailed('请先登录')
        raise AuthenticationFailed('请先登录')


def check_name(realname):
    """验证真实姓名"""
    return True


def check_id(idnum):
    """验证身份证号"""
    return True
